﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sharp.Interprocess;
using System.Threading.Tasks;
using System.Threading;
namespace SharedCollectionTesterApp
{
    class Program
    {
        private static int m_CollectionCount = 0;
        private static bool m_IsRunning;
        static void Main(string[] args)
        {
            var sharedCollection = new SharedCollection<long>("TestMap", 0,true,100);
            m_IsRunning = true;
            var inputThread = new Thread(new ThreadStart(() => {
                while (m_IsRunning)
                {
                    if (sharedCollection.Count != m_CollectionCount)
                    {
                        var updatedCollection = sharedCollection.ToList();
                        if (updatedCollection.Any())
                        {
                            m_CollectionCount = updatedCollection.Count;
                            Console.WriteLine("added value to shared collection:{0}", updatedCollection.Last());
                        }
                        else
                        {
                            Console.WriteLine("stored collection is empty");
                        }
                    }
                    Thread.Sleep(250);
                }
            }));
            inputThread.IsBackground = true;
            inputThread.Name = "Input Thread";
            inputThread.Start();

            string input = "";
            while (input.ToLower() != "exit")
            {
                input = Console.ReadLine();
                long parsedInput = 0;
                if (long.TryParse(input, out parsedInput))
                {
                    sharedCollection.Add(parsedInput);
                }
                else if (input.ToLower() == "list")
                {
                    var fetchedCollection = sharedCollection.ToList();
                    if (!fetchedCollection.Any())
                    {
                        Console.WriteLine("no data is stored..");
                    }
                    else
                    {
                        Console.WriteLine("listing...");
                        foreach (var item in fetchedCollection)
                        {
                            Console.WriteLine(item);
                        }
                        Console.WriteLine("done listing");
                    }
                }
            }

            m_IsRunning = false;
            Thread.Sleep(500);
            inputThread.Join(500);
            try
            {
                inputThread.Abort();
            }
            catch { }
        }
    }
}
